package com.ultrapower.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.scan.Traced;
import com.ultrapower.commons.shiro.PasswordHash;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.Product;
import com.ultrapower.service.IProductService;
import com.ultrapower.service.IUserService;
import com.ultrapower.task.UploadEnterprise;
import com.ultrapower.task.UploadUser;

/**
 * @description：产品
 * @author：polly
 * @date：2018-6-11 14:29:29
 */
@Controller
@RequestMapping("/product")
public class ProductController extends BaseController{

	@Autowired
    private IProductService productService;
	@Autowired
    private IUserService userService;
	@Autowired
    private PasswordHash passwordHash;
	
	/**
     * 产品管理页
     *
     * @return
     */
    @GetMapping("/manager")
    public String manager() {
        return "admin/product/product";
    }
    
    /**
     *产品管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(Product product, Integer page, Integer limit, String sort, String order) {
    	sort = "createTime";
    	order = "asc";
    	 Map<String, Object> condition = new HashMap<String, Object>();
    	if (StringUtils.isNotBlank(product.getName())) {
            condition.put("name", product.getName());
        }
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        pageInfo.setCondition(condition);
        productService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * 添加产品页
     *
     * @return
     */
    @GetMapping("/addProduct")
    public String addProduct() {
        return "admin/product/productAdd";
    }
    
    /**
     * 产品列表
     *
     * @return
     */
    @RequestMapping("/treeGrid")
    @ResponseBody
    public Object treeGrid() {
        return productService.selectTreeGrid();
    }
    
    @Traced(name="上传产品图片")
    @PostMapping("/photoUpload")
    @ResponseBody
    public String uploadimg(HttpServletRequest request,MultipartFile file){
    	JSONObject json = new JSONObject();
    	JSONObject jsonData = new JSONObject();
        try {
        	//文件上传路径
        	request.setCharacterEncoding("UTF-8");
            String path = request.getServletContext().getRealPath("/");
			String filename = file.getOriginalFilename();
			System.out.println(path+"/"+filename);
			//写入本地磁盘
			InputStream is = file.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			path = "/home/enterprise/file/images/";
			File tmpfile = new File(path);
			if(!tmpfile.exists()){
				tmpfile.mkdir();
			}
			OutputStream os = new FileOutputStream(new File(path+filename));
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
	    	json.put("code", 0);
	    	json.put("msg", "");
	    	jsonData.put("src", filename);
	    	json.put("data", jsonData);
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
    }
    
    @PostMapping("/fileUpload")
    @ResponseBody
    public String uploadFile(HttpServletRequest request,MultipartFile file){
    	JSONObject json = new JSONObject();
    	JSONObject jsonData = new JSONObject();
        try {
        	//文件上传路径
        	request.setCharacterEncoding("UTF-8");
            String path = request.getServletContext().getRealPath("/");
			String filename = file.getOriginalFilename();
			//写入本地磁盘
			InputStream is = file.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			path = "/home/enterprise/file/tmpfile/";
			File tmpfile = new File(path);
			if(!tmpfile.exists()){
				tmpfile.mkdir();
			}
			OutputStream os = new FileOutputStream(new File(path+filename));
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			new UploadEnterprise().doUpload(path+filename);
	    	json.put("code", 0);
	    	json.put("msg", "");
	    	jsonData.put("src", filename);
	    	json.put("data", jsonData);
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
    }
    
    @PostMapping("/userFileUpload")
    @ResponseBody
    public String userUploadFile(HttpServletRequest request,MultipartFile file){
    	JSONObject json = new JSONObject();
    	JSONObject jsonData = new JSONObject();
        try {
        	//文件上传路径
        	request.setCharacterEncoding("UTF-8");
            String path = request.getServletContext().getRealPath("/");
			String filename = file.getOriginalFilename();
			//写入本地磁盘
			InputStream is = file.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			path = "/home/enterprise/file/userFile/";
			File tmpfile = new File(path);
			if(!tmpfile.exists()){
				tmpfile.mkdir();
			}
			OutputStream os = new FileOutputStream(new File(path+filename));
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			new UploadUser().doUpload(path+filename,userService,passwordHash);
	    	json.put("code", 0);
	    	json.put("msg", "");
	    	jsonData.put("src", filename);
	    	json.put("data", jsonData);
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
    }
    
    /**
     * 添加产品
     *
     * @param product
     * @return
     */
    @Traced(name="添加产品")
    @PostMapping("/add")
    @ResponseBody
    public Object add(@Valid Product product) {
//    	String str = product.getPicture();
//    	String picture = str.substring(str.indexOf("file")-1);
    	//product.setPicture(picture);
    	productService.insert(product);
        return renderSuccess("添加成功");
    }
    
    /**
     * 编辑产品页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, int id) {
    	Product product = productService.selectProById(id);
        model.addAttribute("product", product);
        return "admin/product/productEdit";
    }
    
    /**
     * 编辑产品
     *
     * @param Product
     * @return
     */
    @Traced(name="编辑产品")
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@Valid Product product) {
    	productService.updateById(product);
        return renderSuccess("修改成功！");
    }
    
    /**
     * 分享产品页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/sharePage")
    public String sharePage(Model model, int id) {
    	Product product = productService.selectProById(id);
        model.addAttribute("product", product);
        return "admin/product/productShare";
    }
}
